//
//  OneKeyRepairViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/21.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "OneKeyRepairViewController.h"
#import "OneKeyRepairMainTableCell.h"
#import "SelectRepairRegionViewController.h"
#import "SelectAddressTableViewCell.h"
#import "SelectRepairDetailRegionTableCell.h"
#import "HSRepairPickerView.h"
#import <TXScrollLabelView.h>

static NSString *DefaultAddressCellIdentifier = @"DefaultAddressCellIdentifier";
static NSString *PositionCellIdentifier = @"PositionCellIdentifier";
static NSString *EmptyRegionCellIdentifier = @"EmptyRegionCellIdentifier";
static NSString *SelectRepairDetailCellID = @"SelectRepairDetailCellID";
static NSString *RepairRegionCellIdentifier = @"RepairRegionCellIdentifier";
static NSString *UploadImageCellIdentifier = @"UploadImageCellIdentifier";
static NSString *QuestionCellIdentifier = @"QuestionCellIdentifier";
static NSString *ServiceTimeCellIdentifier = @"ServiceTimeCellIdentifier";
static NSString *QuestionPlaceholder = @"请描述报修问题详情";
@interface OneKeyRepairViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UITextViewDelegate,OneKeyRepairTableCellDelegate,OneKeyRepairUploadImageTableCellDelegate,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>

@property (nonatomic,strong)UIScrollView *scrollView;

/**
 默认地址
 */
@property (nonatomic,strong)AddressModel *defaultAddress;

/**
 图片数组
 */
@property (nonatomic,strong)NSMutableArray *imgUrlArray;

@property (nonatomic,strong)TZImagePickerController *imagePickerVC;

@property (nonatomic,strong)UIImagePickerController *defaultImagePickerVC;

/**
 问题描述
 */
@property (nonatomic,copy)NSString *questionDescription;

/**
 某一天时间
 */
@property (nonatomic,strong)NSMutableArray *serviceTimeArr;

/**
 上下午时间
 */
@property (nonatomic,strong)NSMutableArray *timeBeansArr;

/**
 服务时间
 */
@property (nonatomic,copy)NSString *selectedServiceTime;

@end

@implementation OneKeyRepairViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"一键报修";
    [self createView];
    [self getDefaultAddress];
    [self getServiceTime];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)getServiceTime{
    NSDictionary *dict = @{@"parent_id":@"-1"};
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kGetMaintailServiceTimes parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        id resultData = responseObject[@"data"];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSArray class]] && [resultData count]){
            for (NSDictionary *serviceTimeDic in resultData) {
                NSString *serviceTime = [serviceTimeDic objectForKey:@"service_time"];
                NSArray *timeBeans = [serviceTimeDic objectForKey:@"timeBeans"];
                NSMutableArray *deadTimeArr = [NSMutableArray array];
                for (NSDictionary *timeDic in timeBeans) {
                    NSString *start_time = [timeDic objectForKey:@"start_time"];
                    NSString *end_time = [timeDic objectForKey:@"end_time"];
                    [deadTimeArr addObject:[NSString stringWithFormat:@"%@-%@",start_time,end_time]];
                }
                [self.timeBeansArr addObject:deadTimeArr];
                [self.serviceTimeArr addObject:serviceTime];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)getDefaultAddress{
    NSDictionary *dict = @{@"member_id":[NSString emptyStr:K_UserDefault_Read(CustomerUserID)],@"member_token":[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)]};
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kGetDefaultAddress parameters:dict andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        id resultData = responseObject[@"data"];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSDictionary class]] && [[resultData allValues] count]){
            weakSelf.defaultAddress = [AddressModel yy_modelWithDictionary:resultData];
            [weakSelf.tableView reloadData];
        }
    } Failure:^(NSError *error) {
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}

- (void)createView{
    
    NSString *scrollTitle = [[NSUserDefaults standardUserDefaults]objectForKey:@"kSavedScrollMessage"];
    if (scrollTitle == nil) {
        scrollTitle = @"";
    }
    TXScrollLabelView *scrollLabelView = [TXScrollLabelView scrollWithTitle:scrollTitle type:0 velocity:3 options:UIViewAnimationOptionTransitionFlipFromTop];
    scrollLabelView.frame = CGRectMake(0, 0, F_DEVICE_W, 44);
    scrollLabelView.backgroundColor = [HSPublic colorWithHexString:@"FFF68F"];
    scrollLabelView.scrollTitleColor = [HSPublic colorWithHexString:@"E51C23"];
    [self.scrollView addSubview:scrollLabelView];
    [scrollLabelView beginScrolling];
    
    self.tableView.frame = CGRectMake(0, 44, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0));
    self.tableView.bounces = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.tableView];
    self.scrollView.contentSize = CGSizeMake(F_DEVICE_W, self.tableView.viewBottom + 100 + 44);
    [self.tableView registerClass:[SelectAddressTableViewCell class] forCellReuseIdentifier:DefaultAddressCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairMainTableCell class] forCellReuseIdentifier:PositionCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairEmptyRegionTableCell class] forCellReuseIdentifier:EmptyRegionCellIdentifier];
    [self.tableView registerClass:[SelectedRepairRegionInfoTableCell class] forCellReuseIdentifier:SelectRepairDetailCellID];
    [self.tableView registerClass:[OneKeyRepairRegionTableCell class] forCellReuseIdentifier:RepairRegionCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairUploadImageTableCell class] forCellReuseIdentifier:UploadImageCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairQuestionDescriptionTableCell class] forCellReuseIdentifier:QuestionCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairSelectServiceTimeTableCell class] forCellReuseIdentifier:ServiceTimeCellIdentifier];
    
    UIButton *appointButton = [UIButton buttonWithType:UIButtonTypeCustom];
    appointButton.frame = CGRectMake(30, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(20), F_DEVICE_W - 60, 50);
    appointButton.layer.cornerRadius = 6;
    appointButton.layer.masksToBounds = YES;
    [appointButton setBackgroundColor:[HSPublic colorWithHexString:@"333333"]];
    [appointButton setImage:[UIImage imageNamed:@"OneKeyRepairWhite"] forState:UIControlStateNormal];
    [appointButton setImage:[UIImage imageNamed:@"OneKeyRepairWhite"] forState:UIControlStateSelected];
    [appointButton setTitle:@"立即报修" forState:UIControlStateNormal];
    [appointButton setTitle:@"立即报修" forState:UIControlStateSelected];
    [appointButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [appointButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [appointButton addTarget:self action:@selector(appointmentAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appointButton];
    
    NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:@"kSavedPriceHelpUrl"];
    if (url != nil) {
        UIButton *priceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        priceButton.frame = CGRectMake(F_DEVICE_W - 120, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(20) - 60, 110, 43);
        priceButton.layer.cornerRadius = 4;
        priceButton.layer.masksToBounds = YES;
        [priceButton setBackgroundColor:[HSPublic colorWithHexString:@"259B24"]];
        [priceButton setTitle:@"查看参考报价" forState:UIControlStateNormal];
        priceButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [priceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [priceButton addTarget:self action:@selector(priceButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:priceButton];
    }
    
    
    self.selectedServiceTime = @"";
//    self.imagePickerVC = [[TZImagePickerController alloc]initWithMaxImagesCount:6 delegate:self];
//    self.imagePickerVC.showPhotoCannotSelectLayer = YES;
//    self.imagePickerVC.allowTakePicture = YES;
//    self.imagePickerVC.allowTakeVideo = NO;
//    self.imagePickerVC.allowPickingVideo = NO;
//    self.imagePickerVC.allowPickingGif = NO;
//    self.imagePickerVC.sortAscendingByModificationDate = NO;
//    self.imagePickerVC.notScaleImage = NO;
    
}

- (void)priceButtonAction: (UIButton *)sender {
    
    NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:@"kSavedPriceHelpUrl"];
    
    BaseWebViewViewController *webView = [BaseWebViewViewController new];
    webView.urlStr = url;
    webView.titleStr = @"参考报价";
    TAB_PUSH(self, webView,YES);
    
}

- (void)appointmentAction:(UIButton *)sender{
    AutoWeakSelf
    if (k_Is_Empty(self.defaultAddress.address_id)) {
        [self showErrorTipWithTitle:@"请选择地址"];
        return;
    }
    if (!self.isPop) {
        [self showErrorTipWithTitle:@"请选择维修区域"];
        return;
    }
    if (k_Is_Empty(self.selectedServiceTime)) {
        [self showErrorTipWithTitle:@"请选择服务时间"];
        return;
    }
    if ([self.imgUrlArray count]>6) {
        [self showErrorTipWithTitle:@"上传凭证最多6张!"];
        return;
    }
    
    NSMutableArray *repairParts = [NSMutableArray array];
    NSMutableArray *repairName = [NSMutableArray array];
    for (SelectRepairModel *model in self.popArray) {
        [repairParts addObject:model.parts_id];
        [repairName addObject:model.parts_name];
    }

    NSArray *separatedArr = [self.selectedServiceTime componentsSeparatedByString:@"\n"];
    NSMutableString *serviceStartTime = nil;
    NSMutableString *serviceEndTime = nil;
    if (separatedArr.count == 2) {
        NSArray *divideArr = [separatedArr.lastObject componentsSeparatedByString:@"-"];
        if (divideArr.count == 2) {
            serviceStartTime = [NSMutableString stringWithFormat:@"%@ %@",separatedArr.firstObject,divideArr.firstObject];
            serviceEndTime = [NSMutableString stringWithFormat:@"%@ %@",separatedArr.firstObject,divideArr.lastObject];
        }
    }
    [self showTipWithTitle:@"正在提交"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)]  forKey:@"member_id"];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
    [dict setObject:self.defaultAddress.address_id forKey:@"address_id"];//地址id
    [dict setObject:self.questionDescription?:@"" forKey:@"maintail_remark"];//维修问题描述
    [dict setObject:[self.imgUrlArray componentsJoinedByString:@","]?:@"" forKey:@"maintail_imgs"];//维修图片路径 多张用逗号隔开
    [dict setObject:[repairParts componentsJoinedByString:@","]?:@"" forKey:@"parts_ids"];//维修部位id 多个逗号隔开
    [dict setObject:[repairName componentsJoinedByString:@","]?:@"" forKey:@"parts_names"];//维修部位名称 多个逗号隔开
    [dict setObject:serviceStartTime?:@"" forKey:@"service_start_time"];//服务开始时间
    [dict setObject:serviceEndTime?:@"" forKey:@"service_end_time"];//服务结束时间
    [dict setObject:k_Is_Empty(self.defaultAddress.address_longitude)?@"":self.defaultAddress.address_longitude forKey:@"address_longitude"];//经度
    [dict setObject:k_Is_Empty(self.defaultAddress.address_latitude)?@"":self.defaultAddress.address_latitude forKey:@"address_latitude"];//纬度

    [[QYNetManager sharedManager]POST:kInsertMaintailOrder parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
        else if ([responseObject[@"status"] isEqualToString:@"pending"]|| [responseObject[@"data"] isKindOfClass:[NSNull class]]){
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            NSInteger result = [responseObject[@"data"] integerValue];
            if (result) {
                [weakSelf showSubmitSuccessPageWithTitle:@"报修已提交" Somebody:@"师傅电联" ButtonTitle:@"查看报修"];
            }else{
                [weakSelf showErrorTipWithTitle:@"下单失败、请完善报修"];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}

/**
 查看报修
 */
- (void)checkOutAppointment{
    [self.navigationController popToRootViewControllerAnimated:NO];
    TAB_SELECT(1)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter]postNotificationName:kPostNotificationForRepairOrder object:@{@"postIndex":@"1"} userInfo:nil];
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1 &&self.isPop&&[self.popArray count]==3){
        SelectRepairModel *model = self.popArray[2];
        if ([HSPublic hsBoundingRectWithWidthString:model.parts_name SizeHeight:50 Font:[UIFont systemFontOfSize:20]]>(F_DEVICE_W/2.0-60)) {
            return 2;
        }else{
            return 1;
        }
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //地址
    if (indexPath.section == 0) {
        if (!k_Is_Empty(self.defaultAddress.address_id)) {
            SelectAddressTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultAddressCellIdentifier];
            [cell cellForLayout:self.defaultAddress];
            return cell;
        }else{
            OneKeyRepairMainTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:PositionCellIdentifier];
            return cell;
        }
        
    }
    //选择维修区域
    else if (indexPath.section == 1){
        //pop必带数据回来。
        if (self.isPop) {
            if (indexPath.row == 0) {
                OneKeyRepairRegionTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:RepairRegionCellIdentifier];
                [cell cellForLayout:self.popArray];
                return cell;
            }else{
                SelectedRepairRegionInfoTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:SelectRepairDetailCellID];
                SelectRepairModel *model = self.popArray[2];
                cell.nameLabel.text = model.parts_name;
                return cell;
            }
        }else{
            OneKeyRepairEmptyRegionTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:EmptyRegionCellIdentifier];
            return cell;
        }
        
    }
    //维修拍照
    else if (indexPath.section == 2){
        OneKeyRepairUploadImageTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:UploadImageCellIdentifier];
        cell.delegate = self;
        cell.dataSource = self.imgUrlArray;
        return cell;
    }
    //报修问题详情
    else if (indexPath.section == 3){
        OneKeyRepairQuestionDescriptionTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:QuestionCellIdentifier];
        cell.textView.delegate = self;
        cell.textView.text = self.questionDescription?:QuestionPlaceholder;
        return cell;
    }
    //服务时间
    else if (indexPath.section == 4){
        OneKeyRepairSelectServiceTimeTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:ServiceTimeCellIdentifier];
        cell.delegate = self;
        [cell cellForServiceTimeLayout:self.selectedServiceTime];
        return cell;
    }
    return nil;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        GlobalAddressManagerViewController *address = [[GlobalAddressManagerViewController alloc]init];
        AutoWeakSelf
        address.addressBlock = ^(AddressModel * _Nonnull addressModel) {
            weakSelf.defaultAddress = addressModel;
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        TAB_PUSH(self, address, YES);
    }
    else if (indexPath.section == 1){
        SelectRepairRegionViewController *repair = [[SelectRepairRegionViewController alloc]init];
        TAB_PUSH(self, repair, YES);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (!k_Is_Empty(self.defaultAddress.address_id)) {
            return 75.f;
        }
        return 50.f;
    }
    else if (indexPath.section == 1){
        return 70.f;
    }else if (indexPath.section == 2){
        return 100.f;
    }else if (indexPath.section == 3){
        return 150.f;
    }else{
        return 50.f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10.f;
    }else if (section == 1){
        return 50.f;
    }else if (section == 2){
        return 40.f;
    }
    else if (section == 4){
        return 30.f;
    }else{
        return 0.001;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 10)];
    backView.backgroundColor = [UIColor appColor];
    if (section == 0) {
        return backView;
    }else if (section == 1){
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 50);
        UIView *whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, F_DEVICE_W, 40)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [backView addSubview:whiteView];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, F_DEVICE_W-20, 40)];
        titleLabel.text = @"维修需求";
        titleLabel.font = Font(16);
        titleLabel.textColor = [HSPublic colorWithHexString:@"#808080"];
        [whiteView addSubview:titleLabel];
        return backView;
    }else if (section == 2){
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 40);
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, F_DEVICE_W-20, 40)];
        titleLabel.text = @"维修拍照";
        titleLabel.font = Font(16);
        titleLabel.textColor = [HSPublic colorWithHexString:@"#808080"];
        [backView addSubview:titleLabel];
        return backView;
    }
    else if (section == 4){
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 30);
        return backView;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}


#pragma mark - OneKeyRepairUploadImageTableCellDelegate
- (void)uploadImageTableCellAddImage:(NSIndexPath *)indexPath{
    if (self.imgUrlArray.count == 6) {
        [self showErrorTipWithTitle:@"已达到最大数量"];
        return;
    }
    //选中后的缓存勾选没有Api去除、每次重新创建得了。
    self.imagePickerVC = [[TZImagePickerController alloc]initWithMaxImagesCount:6 delegate:self];
    self.imagePickerVC.showPhotoCannotSelectLayer = YES;
    self.imagePickerVC.allowTakePicture = YES;
    self.imagePickerVC.allowTakeVideo = NO;
    self.imagePickerVC.allowPickingVideo = NO;
    self.imagePickerVC.allowPickingGif = NO;
    self.imagePickerVC.sortAscendingByModificationDate = NO;
    self.imagePickerVC.notScaleImage = NO;
    self.imagePickerVC.maxImagesCount = 6 - [self.imgUrlArray count];
//    self.imagePickerVC.selectedAssets = [NSMutableArray arrayWithCapacity:0];
//    self.imagePickerVC.selectedModels = [NSMutableArray arrayWithCapacity:0];
//    self.imagePickerVC.selectedAssetIds = [NSMutableArray arrayWithCapacity:0];
    AutoWeakSelf
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            NSLog(@"%@",photos);
            __block typeof(weakSelf) strongSelf = weakSelf;
            NSString *urlStr = [NSString stringWithFormat:@"%@%@",kServiceID,kUploadRepairImage];
            [strongSelf showLoading];
            [[QYNetManager sharedManager]upLoadImageWithURL:urlStr parameters:nil andImageInfoArr:@[photos,assets] SuccessBlock:^(id responseObject) {
                [strongSelf hideLoading];
                if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                    NSArray *imgUrl = responseObject[@"data"];
                    [strongSelf.imgUrlArray addObjectsFromArray:imgUrl];
                    [strongSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
                }else{
                    [strongSelf showTipWithTitle:responseObject[@"error"]];
                }
            } Failure:^(NSError *error) {
                [strongSelf hideLoading];
                [strongSelf showErrorTipWithTitle:error.localizedDescription];
            }];
        }];
        [self presentViewController:self.imagePickerVC animated:YES completion:nil];
    }];
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            if (self.imgUrlArray.count == 6) {
                [self showErrorTipWithTitle:@"已达到最大数量"];
                return;
            }else{
                weakSelf.defaultImagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                [weakSelf presentViewController:weakSelf.defaultImagePickerVC animated:YES completion:nil];
            }
        }
    }];
    UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [cancelAct setValue:[UIColor redColor] forKeyPath:@"titleTextColor"];
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    [aleVC addAction:cancelAct];
    [self presentViewController:aleVC animated:YES completion:nil];
    
}

- (void)uploadImageTableCellTapHaveALook:(NSIndexPath *)indexPath{
    HSImageScrollViewController *scrollVC = [[HSImageScrollViewController alloc]init];
    scrollVC.imgUrlArr = self.imgUrlArray;
    scrollVC.index = indexPath.row;
    [self.navigationController presentViewController:scrollVC animated:YES completion:nil];
}

//optional
- (void)uploadImageTableCellDeleteImage:(NSIndexPath *)indexPath{
    AutoWeakSelf
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (indexPath.row < [weakSelf.imgUrlArray count]) {
            [weakSelf.imgUrlArray removeObjectAtIndex:indexPath.row];
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }];
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认删除该图片?" preferredStyle:UIAlertControllerStyleAlert];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    [self presentViewController:aleVC animated:YES completion:nil];
}

#pragma mark - OneKeyRepairTableCellDelegate
- (void)serviceTimeTapEvent{
    HSRepairPickerView *pickView = [[HSRepairPickerView alloc] init];
    pickView.components = 2;
    NSArray *dataArr = @[self.serviceTimeArr,self.timeBeansArr];
    pickView.pickViewArr = dataArr;
    AutoWeakSelf
    [pickView didFinishSelectedDate:^(NSArray *selectIndexs) {
        NSMutableString *mString = [NSMutableString string];
        NSInteger repairIndex = 0;
        for (NSInteger i = 0; i < 2; i++) {
            if (i == 0) {
                NSArray *serviceArr = [dataArr objectAtIndex:i];
                NSInteger seletedIndex = [[selectIndexs objectAtIndex:i] integerValue];
                NSString *str = [serviceArr objectAtIndex:seletedIndex];
                [mString appendFormat:@"%@\n",str];
                repairIndex = seletedIndex;
            }else{
                NSArray *timeBeans = [[dataArr objectAtIndex:i] objectAtIndex:repairIndex];
                NSInteger seletedIndex = [[selectIndexs objectAtIndex:i] integerValue];
                NSString *seletedStr = [timeBeans objectAtIndex:seletedIndex];
                [mString appendString:seletedStr];
            }
        }
        weakSelf.selectedServiceTime = mString;
        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:4]] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:QuestionPlaceholder]) {
        textView.text = @"";
        textView.textColor = [HSPublic colorWithHexString:@"333333"];
    }else{
        textView.textColor = [HSPublic colorWithHexString:@"#808080"];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = QuestionPlaceholder;
        textView.textColor = [HSPublic colorWithHexString:@"#808080"];
    }else{
        textView.textColor = [HSPublic colorWithHexString:@"333333"];
        self.questionDescription = textView.text;
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //发协议
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kServiceID,kUploadUserImage];
    AutoWeakSelf
    [[QYNetManager sharedManager]upLoadSingeImage:urlStr parameters:nil andImage:image andImageName:currentTimeString SuccessBlock:^(id responseObject) {
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            NSString *currentImgPath = responseObject[@"data"];
            [weakSelf.imgUrlArray addObject:currentImgPath];
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
        }else{
            [weakSelf showTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}


#pragma mark - GETTER
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,NAVIGATION_BAR_HEIGHT, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0))];
        _scrollView.delegate = self;
        _scrollView.showsVerticalScrollIndicator = NO;
    }
    return _scrollView;
}

- (NSMutableArray *)timeBeansArr{
    if (!_timeBeansArr) {
        _timeBeansArr = [NSMutableArray array];
    }
    return _timeBeansArr;
}

- (NSMutableArray *)serviceTimeArr{
    if (!_serviceTimeArr) {
        _serviceTimeArr = [NSMutableArray array];
    }
    return _serviceTimeArr;
}


- (NSMutableArray *)imgUrlArray{
    if (!_imgUrlArray) {
        _imgUrlArray = [NSMutableArray array];
    }
    return _imgUrlArray;
}

- (UIImagePickerController *)defaultImagePickerVC{
    if (!_defaultImagePickerVC) {
        _defaultImagePickerVC = [[UIImagePickerController alloc]init];
        _defaultImagePickerVC.delegate = self;
        _defaultImagePickerVC.allowsEditing = NO;
    }
    return _defaultImagePickerVC;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
